const Service = require('egg').Service;

class ResumeService extends Service {
    // 创建/上传简历（仅支持文件URL）
    async create(resumeData) {
        const { ctx } = this;
        const userId = ctx.state.user_id;
        if (!userId) throw new Error('请先登录');

        // 强制校验file_url存在（模型已约束，这里二次确认）
        if (!resumeData.file_url) throw new Error('简历文件URL不能为空');

        const resume = await ctx.model.Resume.create({
            ...resumeData,
            user_id: userId,
            created_at: new Date(), // 手动设置创建时间
            updated_at: new Date()  // 手动设置更新时间
        });
        return resume;
    }

    // 获取用户的简历列表（字段简化）
    async getUserResumes(userId, query) {
        const { ctx } = this;
        const { page = 1, pageSize = 10 } = query;

        const options = {
            where: { user_id: userId },
            attributes: ['resume_id', 'file_url', 'visibility', 'created_at', 'updated_at'], // 只返回模型存在的字段
            limit: parseInt(pageSize),
            offset: (parseInt(page) - 1) * parseInt(pageSize),
            order: [['created_at', 'DESC']]
        };

        const { count, rows } = await ctx.model.Resume.findAndCountAll(options);
        return {
            list: rows,
            pagination: { page: parseInt(page), pageSize: parseInt(pageSize), total: count, totalPages: Math.ceil(count / pageSize) }
        };
    }

    // 更新简历（仅支持更新file_url和visibility，且手动维护updated_at）
    async update(resumeId, updateData) {
        const { ctx } = this;
        const resume = await ctx.model.Resume.findByPk(resumeId);
        if (!resume) throw new Error('简历不存在');

        // 权限校验
        const currentUserId = ctx.state.user_id;
        const isAdmin = ctx.state.type === 'admin';
        if (!isAdmin && resume.user_id.toString() !== currentUserId.toString()) {
            throw new Error('无权更新此简历');
        }

        // 手动更新时间戳
        await resume.update({
            ...updateData,
            updated_at: new Date()
        });
        return resume;
    }

   // app/service/resume.js
async getResumeById(resumeId) {
    const { ctx } = this;
    const resume = await ctx.model.Resume.findByPk(resumeId);
    if (!resume) throw new Error('简历不存在');

    // 权限校验逻辑修改
    const currentUserId = ctx.state.user_id;
    const isAdmin = ctx.state.type === 'admin';
    const isOwner = currentUserId && resume.user_id.toString() === currentUserId.toString();

    // 允许访问的情况：管理员 || 本人 || 简历为公开（visibility=1）
    if (!isAdmin && !isOwner && resume.visibility !== 1) {
        throw new Error('无权查看此简历');
    }

    return resume;
}

    async delete(resumeId) {
        const { ctx } = this;
        const resume = await ctx.model.Resume.findByPk(resumeId);
        if (!resume) throw new Error('简历不存在');

        // 权限校验
        const currentUserId = ctx.state.user_id;
        const isAdmin = ctx.state.type === 'admin';
        if (!isAdmin && resume.user_id.toString() !== currentUserId.toString()) {
            throw new Error('无权删除此简历');
        }

        await resume.destroy();
        return true;
    }

    async updateVisibility(resumeId, visibility) {
        return this.update(resumeId, { visibility });
    }
     // 新增：获取指定用户的公开简历（visibility=1）
    async getUserPublicResumes(targetUserId, query) {
        const { ctx } = this;
        const { page = 1, pageSize = 10 } = query;

        // 验证目标用户是否存在
        const targetUser = await ctx.model.User.findByPk(targetUserId);
        if (!targetUser) throw new Error('用户不存在');

        const options = {
            where: {
                user_id: targetUserId,
                visibility: 1 // 只查询公开的简历
            },
            attributes: ['resume_id', 'file_url', 'visibility', 'created_at', 'updated_at'],
            limit: parseInt(pageSize),
            offset: (parseInt(page) - 1) * parseInt(pageSize),
            order: [['created_at', 'DESC']]
        };

        const { count, rows } = await ctx.model.Resume.findAndCountAll(options);
        return {
            list: rows,
            pagination: { page: parseInt(page), pageSize: parseInt(pageSize), total: count, totalPages: Math.ceil(count / pageSize) }
        };
    }
}

module.exports = ResumeService;